package job

import (
	"fmt"
	"time"
	"workflow/config"
	"workflow/service"
)

type WorkflowInterval struct {
	ID       string
	Interval int
	Left     int
}

func TickerDaemon() {
	ticker := time.NewTicker(time.Second * 60)
	defer ticker.Stop()
	var cache []WorkflowInterval
	for {
		select {
		case <-ticker.C:
			for index, workflowInterval := range cache {
				if workflowInterval.Left > 0 {
					cache[index].Left = workflowInterval.Left - 1
				} else {
					fmt.Println("启动任务" + workflowInterval.ID)
					trigger, err := service.TickerTrigger(workflowInterval.ID)
					if err != nil {
						panic(err)
					}
					config.TriggerChannel <- trigger.ID
					cache[index].Left = workflowInterval.Interval
				}
			}
		case <-config.ConfigChannel:
			cache = make([]WorkflowInterval, 0)
			projects, err := service.ListProjects()
			if err != nil {
				panic(err)
			}
			for _, project := range projects {
				for _, workflow := range project.Workflows {
					if workflow.Interval > 0 {
						cache = append(cache, WorkflowInterval{
							ID:       workflow.ID,
							Interval: workflow.Interval,
							Left:     workflow.Interval,
						})
					}
				}
			}
			fmt.Println("配置定时器")
		}
	}
}
